package com.tsfyun.scm.job;

import cn.hutool.core.util.StrUtil;
import com.tsfyun.common.base.dto.CostWriteOffDTO;
import com.tsfyun.common.base.vo.CustomerSimpleVO;
import com.tsfyun.scm.service.customer.ICustomerService;
import com.tsfyun.scm.stream.send.ScmProcessor;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**=
 * 核销定时器，每日凌晨3点执行
 */
@JobHandler(value="writeOffJobHandler")
@Component
@Slf4j
public class WriteOffJobHandler extends IJobHandler {

    @Autowired
    private ICustomerService customerService;

    @Resource
    private ScmProcessor scmProcessor;

    @Override
    public ReturnT<String> execute(String param) throws Exception {
        //消息通知核销
        //获取所有的已审核客户
        customerService.allAuditCustomer().stream().forEach(this::accept);
        return SUCCESS;
    }

    private void accept(CustomerSimpleVO customer) {
        log.info("准备自动核销客户【{}】", customer.getName());
        CostWriteOffDTO cwdto = new CostWriteOffDTO();
        cwdto.setTenant("");
        cwdto.setCustomerId(customer.getId());
        try {
            scmProcessor.sendCostWriteOff(cwdto);
        } catch (Exception e) {
            log.error(StrUtil.format("自动核销客户【{}】发送消息异常",customer.getName()),e);
        }
    }
}
